package web;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dto.Student;
import dto.User;
import service.StudentServices;

/**
 * Servlet implementation class AddStudentController
 */
@WebServlet("/DEO/addStudent")
public class AddStudentController extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private StudentServices studentServices;
    
    @Override
    public void init() throws ServletException {
    	studentServices = new StudentServices();
    }
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddStudentController() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.getRequestDispatcher("AddStudent.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		HttpSession session = request.getSession(false);
		User user = (User)session.getAttribute("user");
		
		Student student = new Student();
		
		student.setFname(request.getParameter("fname"));
		student.setLname(request.getParameter("lname"));
		student.setEmail(request.getParameter("email"));
		student.setMobile(request.getParameter("mobile"));
		
		String dob_input = request.getParameter("dob");
		SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");
		try {
			Date dob = df.parse(dob_input);
			student.setDob(dob);
		}catch(Exception e) {
			throw new ServletException(e); 
		}
		
		student.setInsertedBy(user.getUname());
		student.setInsertedOn(new Date());
		
		studentServices.createStudent(student);
		session.setAttribute("student", student);
	}
}
